package com.ztesoft.sca.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.qualitycheck.model.v20160801.GetAudioDataStatusRequest;
import com.aliyuncs.qualitycheck.model.v20160801.GetAudioDataStatusResponse;
import com.aliyuncs.qualitycheck.model.v20160801.GetResultRequest;
import com.aliyuncs.qualitycheck.model.v20160801.GetResultResponse;
import com.aliyuncs.qualitycheck.model.v20160801.UploadAudioDataWithRulesRequest;
import com.aliyuncs.qualitycheck.model.v20160801.UploadAudioDataWithRulesResponse;
import com.ztesoft.sca.common.Constants;
import com.ztesoft.sca.common.SysConstant;
import com.ztesoft.sca.model.AudioSourceDto;
import com.ztesoft.sca.model.DataSetModel;
import com.ztesoft.sca.model.QcSceneModel;
import com.ztesoft.sca.model.RuleModel;
import com.ztesoft.sca.model.ScaAudioResult;
import com.ztesoft.sca.model.TaskAudioRelaModel;
import com.ztesoft.sca.model.TaskModel;
import com.ztesoft.sca.service.RuleService;
import com.ztesoft.sca.service.TaskResultService;
import com.ztesoft.sca.service.TaskService;
import com.ztesoft.sca.util.exception.ExceptionUtil;
import com.ztesoft.sca.util.message.ResponseUtils;
import com.ztesoft.sca.util.seq.SequenceCreator;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import oracle.sql.CLOB;
import com.ztesoft.sca.common.ClobToStringUtil;
/*
 * 质检任务处理 
 * zxz 
 * */

@RestController
public class TaskController {
	private static final Logger logger = Logger.getLogger(AiChatAudioController.class);
	
    @Autowired
    private TaskService taskService; 
    
    @Autowired
    private RuleService ruleService; 
    
    @Autowired
    private TaskResultService taskResultService; 

    //默认文件保存路径
    @Value("${fileUpload.defaultUploadPath}")
    private String defaultUploadPath;
    
    //文件服务器存放地址 目录
    @Value("${fileUpload.filePathUrl}")
    private String filePathUrl;
    
    //请求方的回调地址
    @Value("${sca.FeedbackRecvPath}")
    private String FeedbackRecvPath;
    
    //文件服务器存放地址 实际目录 linux
    @Value("${fileUpload.actualFileServerUrl}")
    private String actualFileServerUrl;
    
	/*
	 * zxz 质检任务 新增
	 * */
    @RequestMapping(value = "/task/addTask.do",method = {RequestMethod.POST})
    public String AddTask(@RequestBody String requestBody,HttpServletRequest request)  {
		JSONObject json = JSONObject.fromObject(requestBody);
		logger.info("-----------------/task/addTask.do-------------");
		if(logger.isDebugEnabled()){
			logger.debug("----requestbody:------"+requestBody);
		}
		if(json == null){
			return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,Constants.INF_DESC_NULL_REQUESTBODY);
		}
	    String taskName = json.getString("taskName");
	    long cId = json.getLong("cId");
	    long setId = json.getLong("setId");
	    long areaId = json.getLong("areaId");
	    JSONArray jsonarr = json.getJSONArray("callList");
	    if(jsonarr == null){
			return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,Constants.INF_DESC_NULL_TASK_AUDIO_FILE);
		}

	    String receiveTaskId="";
       //查询质检规则表
		List<RuleModel> ruleIdStr= null;
		try {
			ruleIdStr = this.ruleService.selectAichatRules(cId);
		} catch (Exception e) {
			logger.error("get sca_rule occur an error!",e);
			return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,ExceptionUtil.getMessage(e));
		}
		List<String> ruleIdList= new ArrayList<String>();
		if(ruleIdStr != null){
			for(RuleModel  stu :  ruleIdStr ){
				ruleIdList.add(Long.toString(stu.getRid()));
			}
		}

       //质检上传 
		List<Map<String, Object>> callMapList = new ArrayList<Map<String, Object>>();
		int autoSplit = 1;
		
        for (int i = 0; i < jsonarr.size(); i++) {  
		    String fileId = jsonarr.getJSONObject(i).getString("fileId");
		    String fileCodec = jsonarr.getJSONObject(i).getString("fileType");
		    String filePath = jsonarr.getJSONObject(i).getString("filePath");
	        //String fileName = fileId+"."+fileCodec;
			String voiceFileUrl = filePath;//+"/"+fileName;
			String sampleRate = "16";
	 	    AudioSourceDto aiAudio = new AudioSourceDto();
	 	    aiAudio.setFile_Id(Long.parseLong(fileId));
	        try {
				List<AudioSourceDto> audioSourceStr=this.taskService.selectAudioSourceList(aiAudio);
				if(!"".equals(audioSourceStr)&&audioSourceStr!=null){
		 	        for(AudioSourceDto  stu :  audioSourceStr ){
		 	        	sampleRate=stu.getSampleRate();
		 	        }
				}
			} catch (Exception e) {
				logger.error("get audioSourceStr occur an error!",e);
				return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,ExceptionUtil.getMessage(e));
			}
	        
			Map<String, Object> callMap = new HashMap<String, Object>();
	        callMap.put("callStartTime", new Date().getTime());
	        callMap.put("clientChannel", 0);
	        callMap.put("sampleRate", sampleRate);
	        callMap.put("serviceChannel", 1);
	        callMap.put("tid", fileId); 
	        callMap.put("voiceFileUrl", voiceFileUrl.trim());
	        callMap.put("ruleIds", ruleIdList);
	        callMap.put("autoSplit", autoSplit);
	        callMapList.add(callMap);
        }
        logger.info("----------callMapList-----"+callMapList);
		try{
			IClientProfile profile = DefaultProfile.getProfile(SysConstant.REGION_ID, SysConstant.ACCESS_KEY_ID, SysConstant.ACCESS_KEY_SECRET);
			DefaultProfile.addEndpoint(SysConstant.ENDPOINT_NAME, SysConstant.REGION_ID, SysConstant.PRODUCT, SysConstant.DOMAIN);
			IAcsClient client = new DefaultAcsClient(profile);
			//指定规则上传待检数据(语音)
			UploadAudioDataWithRulesRequest uploadAudioDataRequest = new UploadAudioDataWithRulesRequest();
	        uploadAudioDataRequest.setAcceptFormat(FormatType.JSON);	        
			Map<String, Object> map = new HashMap<String, Object>();

	        map.put("appKey", SysConstant.APP_KEY);
	        map.put("callList", callMapList);
	        map.put("clientChannel", 1);
	        map.put("sampleRate", 8);
	        map.put("serviceChannel", 0);
	        uploadAudioDataRequest.setJsonStr(JSON.toJSONString(map));
	        UploadAudioDataWithRulesResponse response = client.getAcsResponse(uploadAudioDataRequest);
	       // result = JSON.toJSONString(response);
	        receiveTaskId=response.getData();
	        long taskId ;
	        try {
				taskId = SequenceCreator.getSequence("SCA_TASK_SEQ");
	       	} catch (Exception e) {
	           logger.error("sequenceCreator obtain SCA_TASK_SEQ occur an error!",e);
	           return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,ExceptionUtil.getMessage(e));
	       	}
	        TaskModel aiTask = new TaskModel();
	        aiTask.setTaskId(taskId);
	        aiTask.setTaskName(taskName);
	        aiTask.setSetId(setId);
	        aiTask.setAreaId(areaId);
	        aiTask.setSceneId(cId);
	        aiTask.setStartTime(new Date());
	        aiTask.setStatus(0);
	        aiTask.setAlitaskid(receiveTaskId);
	        //补充任务与音频文件的关联关系
	        try {
	            this.taskService.addTask(aiTask);
	        } catch (Exception e) {
	            logger.error("create SCA_TASK occur an error !",e);
	            return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,ExceptionUtil.getMessage(e));
	        }
		        //音频源质检结果，音频与任务关系
	         List<ScaAudioResult> listAddAudioResult = new ArrayList<ScaAudioResult>();
	         List<TaskAudioRelaModel> listAddAudioTask = new ArrayList<TaskAudioRelaModel>();

	         if(jsonarr.size()>0){
	        	for (int i = 0; i < jsonarr.size(); i++) {  
	 		        Long fileId=Long.parseLong(jsonarr.getJSONObject(i).getString("fileId"));
	 		        listAddAudioTask.add(new TaskAudioRelaModel(fileId,taskId));
	 		       
		 		    Long resultId = 0l;
					try {
						resultId = SequenceCreator.getSequence("SCA_AUDIO_RESULT_SEQ");
					} catch (Exception e) {
						logger.error(" addAudioTask addAudioResult    occur an error!",e);
	 					return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
					}
	 		       listAddAudioResult.add(new ScaAudioResult(resultId,fileId));
	 	        }
 		        try {
 					this.taskService.addAudioTask(listAddAudioTask);
 					this.taskService.addAudioResult(listAddAudioResult);
 				} catch (Exception e) {
 					 logger.error(" addAudioTask addAudioResult    occur an error!",e);
 					 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
 				}
	         }
		}catch (ServerException e) {
			logger.error("service occur an error!",e);
		} catch (ClientException e) {
			logger.error("service occur an error!",e);
		}
		JSONObject jsonStrAll = new JSONObject();
		jsonStrAll.put("taskId", receiveTaskId);
		logger.info("taskId---alisca--is:"+receiveTaskId+" and return json is :"+jsonStrAll);
		return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,jsonStrAll);
	}

	 /*
	 * zxz 轮询查询 质检分析结果状态
	 * 根据质检分析状态  
	 * 获取质检分析结果
	 * */
	@RequestMapping(value = "/task/TaskPollingThreadRun")
	public String TaskPollingThreadRun() throws Exception{
	    String taskStr = "";
	    logger.info("-------------/task/TaskPollingThreadRun---------------------"); 
       //对质检上传之后获取分析结果状态进行轮询
		IClientProfile profile = DefaultProfile.getProfile(SysConstant.REGION_ID, SysConstant.ACCESS_KEY_ID, SysConstant.ACCESS_KEY_SECRET);
		DefaultProfile.addEndpoint(SysConstant.ENDPOINT_NAME, SysConstant.REGION_ID, SysConstant.PRODUCT, SysConstant.DOMAIN);
		IAcsClient client = new DefaultAcsClient(profile);
		
        GetAudioDataStatusRequest getAudioDataStatusRequest = new GetAudioDataStatusRequest();
        getAudioDataStatusRequest.setAcceptFormat(FormatType.JSON);
        Map<String, Object> callMap = new HashMap<String, Object>();
        callMap.put("appKey", SysConstant.APP_KEY);
      
       //查询taskid对应的状态为0的记录
        String receiveStatus="0";
        List<Long> listId= new ArrayList<>();
	    try {
		   List<TaskModel> taskList=this.taskService.selectAichatTaskList(receiveStatus);
	        for(TaskModel pLog : taskList){
	        	//zxz 查询分析状态，是否获取分析完毕
	        	String taskId=pLog.getAlitaskid();
		        callMap.put("taskId", taskId);
		        //callMap.put("tid", pLog.getReceiveFileid());
		        getAudioDataStatusRequest.setJsonStr(JSON.toJSONString(callMap));
		        GetAudioDataStatusResponse response = client.getAcsResponse(getAudioDataStatusRequest);
		        String resultGet = JSON.toJSONString(response);
		        
		        //处理过程状态码       0 – 新建        1 – 语音转换中      2 – 语音转换完成     3 – 分析完成       -1 – 错误
		        JSONArray jsonArray = JSONArray.fromObject(response.getData());  
		        logger.info("--taskId--获取分析结果状态码----"+taskId+"---:"+jsonArray.getJSONObject(0).get("statusCode"));
		        int statusCode=(int) jsonArray.getJSONObject(0).get("statusCode");
		        if(statusCode==3){
		        	taskStr=taskStr+","+taskId;
		        	listId.add(pLog.getTaskId());
		        }
		        
	        }
		} catch (Exception e1) {
			 logger.error(" 获取分析结果状态   occur an error!",e1);
			 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e1));
		}
	   
	   //已经完成语音分析的taskid，执行获取分析结果值
	   if(taskStr.length()>0){
		   //否则直接执行下面的获取分析结果和相关信息更新
		   String taskStrSub=taskStr.substring(1);
		   
		   if(!"".equals(taskStrSub)){
		       //查询音频源表
		       String fileName="";
		       String fileCodec=""; 
		       String filePath="";
		       String voiceFileUrl="";
		       List<ScaAudioResult> listUpdateAudioResult = new ArrayList<ScaAudioResult>();
		       
		       String[] str = taskStrSub.split(","); 
			   for(String aliTaskId:str){
				   //调用 分析结果接口  获取详细内容
				   String ResultInfo=getTaskResult(aliTaskId);
				   logger.info("---预约规范---ResultInfo----"+ResultInfo);
			        //单独获取每个文件的转换结果，音频源结果入库，句子的文本分析，判断该文本的命中规则：半个小时+音频文件创建时间=预约时间 是否处在字段 预约时间和预约结束时间期间内，
			        //如果符合则更新字段预约规范和结果描述
				   if(ResultInfo.length()>0){
					   JSONArray jsonArr = JSONArray.fromObject(ResultInfo);
					   if(jsonArr.size()>0){  
						   for(int i=0;i<jsonArr.size();i++){  
							   JSONObject json = jsonArr.getJSONObject(i);
								JSONArray jsonRules = json.getJSONArray("rules");
						        Long file_Id=Long.parseLong(json.getString("tid"));
						        Long fileId=file_Id;
						        
						 	    AudioSourceDto aiAudio = new AudioSourceDto();
						 	    aiAudio.setFile_Id(file_Id);

						        List<AudioSourceDto> audioSourceStr=this.taskService.selectAudioSourceList(aiAudio);
						         if(audioSourceStr!=null&&audioSourceStr.size()>0){
						 	        for(AudioSourceDto  stu :  audioSourceStr ){
						 	        	fileName=stu.getFileName();
						 	        	fileCodec=stu.getFormat();
						 	        	filePath=stu.getFilePath();
						 	            String fileNames=fileName+"."+fileCodec;
						 	    		voiceFileUrl=filePath+"/"+fileNames;	
						 	    		Date createTime=stu.getCreateTime();
						 	    		String bookTime=stu.getBookTime();
						 	    		String bookEndTime=stu.getBookEndTime();

									 	//时间增加分钟数
							 			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							 			Calendar calendar = Calendar.getInstance();
							 			calendar.setTime(createTime);
							 			 
							 			if(jsonRules.indexOf("半小时后")>-1){
							 			    calendar.add (Calendar.MINUTE, 30);
							 			}else if(jsonRules.indexOf("下午3点")>-1){
							 				SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
							 				String now = sf.format(new Date());
							 				Date nowTime = sf.parse(now);
							 				Long nowTimeLong=nowTime.getTime();
							 				Date afterTime = sf.parse("15:00:00");
							 				Long afterTimeLong=afterTime.getTime();
							 				long seconds=(nowTimeLong-afterTimeLong)/60000;
							 				if(seconds>0){
							 					calendar.add (Calendar.MINUTE, (int)seconds);
							 				}else{
							 					calendar.add (Calendar.MINUTE, 0);
							 				}
							 				
							 			}else{
							 				calendar.add (Calendar.MINUTE, 0);
							 			}
							 			 
							 			String createTimeStrTo=format.format(calendar.getTime());
							 			Date createtimeTo =null;
							 			createtimeTo = format.parse(createTimeStrTo);
							 			long createlongtimeTo=createtimeTo.getTime();
	
							 			//时间从string转换成date类型		 
							 	 		Date bookTimeDate = format.parse(bookTime);
							 	 		long bookTimeLong = bookTimeDate.getTime();
							 	 		Date bookEndTimeDate = format.parse(bookEndTime);
							 	 		long bookEndTimeLong = bookEndTimeDate.getTime();

							 	 		//挂起规范
							        	String handupFlag="";
							        	String isHandup="";
							        	String scaHandupDesc="";
						 	    		String handupTime=stu.getHandupTime();
						 	    		String handupEndTime=stu.getBookEndTime();
						 	    		logger.info("---handupTime---"+handupTime);

						 	    		if(!"".equals(handupTime)&&handupTime!=null&&!"".equals(handupEndTime)&&handupEndTime!=null){
								 	 		Date handupTimeDate = format.parse(handupTime);
								 	 		long handupTimeLong = handupTimeDate.getTime();
								 	 		Date handupEndTimeDate = format.parse(handupEndTime);
								 	 		long handupEndTimeLong = handupEndTimeDate.getTime();
								 	 		
								 	 		if(createlongtimeTo>=handupTimeLong&&createlongtimeTo<=handupEndTimeLong){
									        	 handupFlag="Y";
									        	 isHandup="Y";
									        	 scaHandupDesc="符合挂起规范";
								 	 		}else{
									        	 handupFlag="N";
									        	 isHandup="N";
									        	 scaHandupDesc="不符合挂起规范";
								 	 		}	
						 	    		}
						 	    		
							 	 		//预约规范
							        	String bookFlag="";
							        	String isBook="";
							        	String scaBookDesc="";
							 	 		if(createlongtimeTo>=bookTimeLong&&createlongtimeTo<=bookEndTimeLong){
								        	//SCA_AUDIO_RESULT 更新
							 	 			bookFlag="Y";
							 	 			isBook="Y";
							 	 			scaBookDesc="符合预约规范";
								        	listUpdateAudioResult.add(new ScaAudioResult(fileId,bookFlag,isBook,scaBookDesc,handupFlag,isHandup,scaHandupDesc));
							 	 		}else{
							 	 			bookFlag="N";
							 	 			isBook="N";
							 	 			scaBookDesc="不符合预约规范，不在预约范围时间上门服务";
							 	 			listUpdateAudioResult.add(new ScaAudioResult(fileId,bookFlag,isBook,scaBookDesc,handupFlag,isHandup,scaHandupDesc));
							 	 		}
							 	 		 logger.info("---预约规范---bookFlag----"+bookFlag);

						 	        }
						         }
					       }
					   }
					   
				   } 
				   this.taskResultService.addTaskResult(aliTaskId,ResultInfo);
			   } 
			   
		        if(listUpdateAudioResult!=null&&listUpdateAudioResult.size()>0){
	 		        try {
	 					this.taskService.updateAudioResult(listUpdateAudioResult);
	 				} catch (Exception e) {
	 					 logger.error(" updateAudioResult   occur an error!",e);
	 					 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
	 				}
		       }
		        
			   try {
				   //给状态为3 即完成分析的taskId对应的状态receiveStatus更新操作为1
				    this.taskService.updateAiChatTaskInStr(listId);
				    logger.info("---------updateAiChatTaskInStr----更新成功-taskId------"+taskStrSub);
				} catch (Exception e) {
					logger.error(" updateAiChatTaskInStr occur an error!",e);
				}
		   }
		   
	   }else{
		   logger.info("没有获取分析结果的调度任务"); 
	   }
	   return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,"返回质检复核");
  }
	
	/*
	 * zxz 定时任务执行,
	 * 请求方回调 分析结果
	 * */
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Integer count0 = 1;
    @Scheduled(fixedDelay = 30000)
    public void reportTaskCurrentTimeAfterSleep() throws Exception {
/*        try {
        	logger.info(String.format("===定时任务===第%s次执行，当前时间为：%s", count0++, dateFormat.format(new Date())));
        	TaskPollingThreadRun();
        	addAutoAudioTask();
		} catch (ServerException e) {
			 logger.error(" 定时任务执行   occur an error!",e);
		} catch (ClientProtocolException e) {
			 logger.error(" 定时任务执行   occur an error!",e);
		} catch (ClientException e) {
			 logger.error(" 定时任务执行   occur an error!",e);
		} catch (IOException e) {
			 logger.error(" 定时任务执行   occur an error!",e);
		}*/
    }
    
	/*
	 * 请求方接收质检结果
	 * */
	@RequestMapping(value = "/task/SCAGetTaskResult.do")
	public String getTaskResult(String taskId) {
        String resultGet=null; 
        if("".equals(taskId)){
           taskId="A666C713-862D-4C26-A276-0CC2E30F94B9";
        }
        try{
			IClientProfile profile = DefaultProfile.getProfile(SysConstant.REGION_ID, SysConstant.ACCESS_KEY_ID, SysConstant.ACCESS_KEY_SECRET);
			DefaultProfile.addEndpoint(SysConstant.ENDPOINT_NAME, SysConstant.REGION_ID, SysConstant.PRODUCT, SysConstant.DOMAIN);
			IAcsClient client = new DefaultAcsClient(profile);
			GetResultRequest getResultRequest = new GetResultRequest();
	        getResultRequest.setAcceptFormat(FormatType.JSON);
	        String queryJsonStr = "{\n" +
	                "\"appKey\": \"" + SysConstant.APP_KEY + "\",    \n" +
	                "\"taskId\": \""+taskId+"\"\n" +
	                "}";
	        getResultRequest.setJsonStr(queryJsonStr);
	        GetResultResponse responseGet = client.getAcsResponse(getResultRequest);
	        
	        JSONArray jsonArray = JSONArray.fromObject(responseGet.getData());  
	        resultGet=jsonArray.toString();
        }catch (ServerException e) {
        	logger.error(" 请求方接收质检结果   occur an error!",e);
		} catch (ClientException e) {
			logger.error(" 请求方接收质检结果   occur an error!",e);
		}
		return resultGet;
        //return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,resultGet);
	}
	
    /**
     * 获取任务列表
     * @return
     */
    @RequestMapping(value = "/task/jobTablejobList.do",method = {RequestMethod.POST})
    public String jobTablejobList(@RequestBody String requestBody,HttpServletRequest request){
		long id=0l;
		int from=0;//第1页开始
		int size=10; //每页大小  
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		List<TaskModel> list = new ArrayList<>();
		try {
			list = this.taskService.listTask(id,from,size);
		} catch (Exception e) {
			 logger.error(" jobTablejobList occur an error!",e);
			 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
		}
        JSONArray json = new JSONArray();
        String statusStr="";
        String endTime="";
        for(TaskModel pLog : list){
            JSONObject jo = new JSONObject();
            jo.put("taskId", pLog.getTaskId());
            jo.put("taskName", pLog.getTaskName());
            jo.put("startTime", time.format(pLog.getStartTime()));
            
            if(!"".equals(endTime)){
            	endTime=time.format(pLog.getEndTime());
            }
            jo.put("endTime", endTime);
            jo.put("dataSet", "广西质检测试"); //pLog.getSetId()
            if(pLog.getStatus()==1){
            	statusStr="完成";
            }else{
            	statusStr="进行中";
            }
            jo.put("status", statusStr);
            json.add(jo);
        }

		return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,json.toString());
    }
    
    /*
     * 任务详情
     * */
    @RequestMapping(value = "/task/jobTablejobDetail.do",method = {RequestMethod.POST})
    public String jobTablejobDetail(@RequestParam Long jobId,HttpServletRequest request){
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		List<TaskModel> list = new ArrayList<>();
		TaskModel aiChat = new TaskModel();
        aiChat.setTaskId(jobId);
		try {
			list = this.taskService.detailTask(aiChat);
		} catch (Exception e) {
			 logger.error(" jobTablejobDetail occur an error!",e);
			 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
		}
        JSONArray json = new JSONArray();
        String statusStr="";
        String endTime="";
        for(TaskModel pLog : list){
            JSONObject jo = new JSONObject();
            jo.put("taskName", pLog.getTaskName());
            jo.put("startTime", time.format(pLog.getStartTime()));
            
            if(!"".equals(endTime)){
            	endTime=time.format(pLog.getEndTime());
            }
            jo.put("endTime", endTime);
            if(pLog.getStatus()==1){
            	statusStr="完成";
            }else{
            	statusStr="进行中";
            }
            jo.put("status", statusStr);
            json.add(jo);
        }

		return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,json.toString());
    }

    /*
     * 数据集详情
     * */
    @RequestMapping(value = "/task/jobTabledataSet.do",method = {RequestMethod.POST})
    public String jobTabledataSet(@RequestParam Long jobId,HttpServletRequest request){
		List<DataSetModel> list = new ArrayList<>();
		try {
			list = this.taskService.jobTabledataSet(jobId);
		} catch (Exception e) {
			 logger.error(" jobTabledataSet occur an error!",e);
			 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
		}
        JSONArray json = new JSONArray();
        String channelTypeStr="";
        for(DataSetModel pLog : list){
            JSONObject jo = new JSONObject();
            jo.put("id", pLog.getSetId());
            jo.put("name", pLog.getSetName());
            jo.put("hostname", pLog.getSetDomain());            
            if(pLog.getChannelType()==1){
            	channelTypeStr="双轨";
            }else{
            	channelTypeStr="单轨";
            }
            jo.put("audioWay", channelTypeStr);
            jo.put("role", pLog.getSetRoleArn());
            jo.put("fileNum", pLog.getSetFolder());
            
            json.add(jo);
        }

		return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,json.toString());
    }
    
    /*
     * 质检规则
     * */
    @RequestMapping(value = "/task/jobTableruleCheckResult.do",method = {RequestMethod.POST})
    public String jobTableruleCheckResult(@RequestParam Long jobId,HttpServletRequest request) throws SQLException, IOException{
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        //查询分析结果
		CLOB resultContent=null;
		try {
			resultContent = this.taskService.jobTableruleCheckResult(jobId);
		} catch (Exception e) {
			 logger.error(" jobTableruleCheckResult occur an error!",e);
			 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
		}
		//查询规则  
        String resultCon=ClobToStringUtil.ClobToString(resultContent); //大字段处理
        
        JSONArray jsonTaskRulesList = new JSONArray();
        
        if(!"".equals(resultCon)){
	        JSONObject json = JSONObject.fromObject(resultCon.substring(1,resultCon.length()-1));
	        int score=(int) json.get("score");
	        int reviewStatus=(int) json.get("reviewStatus");
	        String hitId=(String) json.get("hitId");
	
	        JSONArray jsonRules = json.getJSONArray("rules");
	        JSONObject rulesObject=new JSONObject();
	        for (int i = 0; i < jsonRules.size(); i++) {  
	        	rulesObject = jsonRules.getJSONObject(i);
	        	JSONObject jsonRule = JSONObject.fromObject(rulesObject);
	        	 String rid=(String) jsonRule.get("rid");
	        	 int hitStatus=(int) jsonRule.get("hitStatus");
	        	 //查询规则详细
	        	 
	     		List<RuleModel> list = new ArrayList<>();
	        	 RuleModel aiChat = new RuleModel();
	             aiChat.setRid(Long.parseLong(rid));
	     		try {
	     			list = this.ruleService.detailRuleTask(aiChat);
	     		} catch (Exception e) {
	     			 logger.error(" ruleService occur an error!",e);
	     			 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
	     		}
	     		
	     		String status="未生效";
	     		String createTime="";
	             JSONObject jo = new JSONObject();
	             for(RuleModel pLog : list){
	                 jo.put("ruleId", rid);
	                 jo.put("ruleName", pLog.getRuleName());
	                 jo.put("ruleDesc", pLog.getScoreName());
	                 jo.put("serviceType", pLog.getScoreSubname());
	                 jo.put("grade", "");
	                 
	                 if(!"".equals(pLog.getCreateTime())){
	                	 createTime=time.format(pLog.getCreateTime());
	                 }
	                 jo.put("createTime", createTime);
	                 
	                 if(pLog.getStatus()==1){
	                	 status="生效";
	                 }
	                 jo.put("status", status);
	                 jo.put("fileNum", "");
	                 jo.put("checkfileNum", "");
	                 jo.put("recheckfileNum", "");
	                 jo.put("reCheckShootfileNum", "");
	                 jo.put("reCheckPrecision", "");
	                 jo.put("deal", "");
	             }
	             
	             jsonTaskRulesList.add(jo);
	        } 
        }

		return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,jsonTaskRulesList.toString());
    }    
    
    /*
     * 质检文件结果
     * */
    @RequestMapping(value = "/task/jobTablefileCheckResult.do",method = {RequestMethod.POST})
    public String jobTablefileCheckResult(@RequestParam Long jobId,HttpServletRequest request) throws SQLException, IOException{
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        //查询分析结果
		CLOB resultContent=null;
		try {
			resultContent = this.taskService.jobTableruleCheckResult(jobId);
		} catch (Exception e) {
			 logger.error(" jobTableruleCheckResult occur an error!",e);
			 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
		}
        String resultCon=ClobToStringUtil.ClobToString(resultContent); //大字段处理
        JSONArray jsonTaskRulesList = new JSONArray();
        
        JSONObject jo = new JSONObject();
        if(!"".equals(resultCon)){
	        JSONObject json = JSONObject.fromObject(resultCon.substring(1,resultCon.length()-1));
	        int score=(int) json.get("score"); //得分
	        int reviewStatus=(int) json.get("reviewStatus"); //复核状态
	        String hitId=(String) json.get("hitId"); //命中ID
	        String tid=(String) json.get("tid"); //文件名 fileName
	        
	        //查询音频源信息  任务id->数据集Id+文件名Id
	 		List<AudioSourceDto> listAudio = new ArrayList<>();
	 		AudioSourceDto aiChatAudio = new AudioSourceDto();
	 		aiChatAudio.setFileName(tid);
			try {
				listAudio = this.taskService.detailAudioSourceTask(aiChatAudio,jobId);
			} catch (Exception e) {
				 logger.error(" detailAudioSourceTask occur an error!",e);
				 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
			}
	        for(AudioSourceDto pLog : listAudio){
	        	 jo.put("fileName", pLog.getFileName()+"."+pLog.getFormat());
	        	 
	        }
	        
	        JSONArray jsonRules = json.getJSONArray("rules");
	        JSONObject rulesObject=new JSONObject();
	        //命中规则数
	        int ruleHitNum=0;
	        //命中规则名称组合
	        String ruleNameStr="";
	        for (int i = 0; i < jsonRules.size(); i++) {  
	        	rulesObject = jsonRules.getJSONObject(i);
	        	JSONObject jsonRule = JSONObject.fromObject(rulesObject);
	        	int ruleHitCount=jsonRule.size();
	        	ruleHitNum=ruleHitNum+ruleHitCount;
	        	String rid=(String) jsonRule.get("rid");
	        	
	     		List<RuleModel> list = new ArrayList<>();
	        	 RuleModel aiChat = new RuleModel();
	             aiChat.setRid(Long.parseLong(rid));
	     		try {
	     			list = this.ruleService.detailRuleTask(aiChat);
	     		} catch (Exception e) {
	     			 logger.error(" ruleService occur an error!",e);
	     			 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
	     		}

	     		//命中规则名
	     		 String ruleName="";
	             for(RuleModel pLog : list){
	                 ruleName=pLog.getRuleName();
	             }
	             ruleNameStr=ruleName+","+ruleNameStr;
	        }
	        
	        jo.put("ruleHitName", ruleNameStr.substring(1));
	        jo.put("ruleHitNum", ruleHitNum);
	        jo.put("recheckStatus", reviewStatus);
	        jo.put("recheckFileNum", "");
	        jo.put("grade", score);	        
        }
        jsonTaskRulesList.add(jo);

		return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,jsonTaskRulesList.toString());
    } 
  
    /*
     * zxz 调用音频源信息    自动创建任务
     * */
    @RequestMapping(value = "/task/addAutoAudioTask.do",method = {RequestMethod.POST})
    public String addAutoAudioTask() throws NumberFormatException, Exception {
    	logger.info("-----------------/task/addAutoAudioTask.do-------------");
    	SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
 	    String receiveTaskId="";       
        String cId = "1001";//固定场景
        String areaId = "1";
        String setIds = "164";
        
        String fileName="";
        String fileCodec=""; 
        String filePath="";
 	    
        //查询场景表 
        String sceneName="";
        Long sceneId=Long.parseLong(cId);
        List<QcSceneModel> sceneStr=this.taskService.selectSceneList(sceneId);
        if(sceneStr != null){
	        for(QcSceneModel  stu :  sceneStr ){
	     	   sceneName=stu.getSceneName();
	    	}
        }
        //查询质检规则表
        List<RuleModel> ruleIdStr=this.ruleService.selectAichatRules(Long.parseLong(cId));
        
        List<String> ruleIdList= new ArrayList<String>();
        if(ruleIdStr != null){
	        for(RuleModel  stu :  ruleIdStr ){
	            ruleIdList.add(Long.toString(stu.getRid()));
	    	}
        }
        //质检上传 
 		int autoSplit=1;
 	    //查询音频源表     0 – 新建        1 – 语音转换中      2 – 语音转换完成     3 – 分析完成       -1 – 错误
		AudioSourceDto aiAudio = new AudioSourceDto();
		aiAudio.setStatus("0");
		List<AudioSourceDto> audioSourceStr=this.taskService.selectAudioSourceList(aiAudio);
		List<Map<String, Object>> callMapList = new ArrayList<Map<String, Object>>();
         
        //更新音频源状态为进行中 ：1
        //fileName+setId 
        List<AudioSourceDto> listUpdate = new ArrayList<AudioSourceDto>();
        String status="1";
         if(audioSourceStr!=null&&audioSourceStr.size()>0){
 	        for(AudioSourceDto  stu :  audioSourceStr ){
 	        	if("0".equals(stu.getStatus())){
	 	        	fileName=stu.getFileName();
	 	        	fileCodec=stu.getFormat();
	 	        	filePath=stu.getFilePath();
	 	        	
	 	            //String fileNames=fileName+"."+fileCodec;
	 	    		String voiceFileUrl=filePath;//+"/"+fileNames;
	 	    		 Map<String, Object> callMap = new HashMap<String, Object>();
	 		        callMap.put("callStartTime", new Date().getTime());
	 		        callMap.put("clientChannel", 0);
	 		        callMap.put("sampleRate", stu.getSampleRate());
	 		        callMap.put("serviceChannel", 1);
	 		        callMap.put("tid", stu.getFile_Id()); 
	 		        callMap.put("voiceFileUrl", voiceFileUrl.trim());
	 		        callMap.put("ruleIds", ruleIdList);
	 		        callMap.put("autoSplit", autoSplit);
	 		        callMapList.add(callMap);
	 		        
	 		       Long file_Id=stu.getFile_Id();
	 		       Long setId=stu.getSetId();
	 		       listUpdate.add(new AudioSourceDto(file_Id,fileName,setId,status));
 	        	}
 	   	    }
 			
 			try{
 				IClientProfile profile = DefaultProfile.getProfile(SysConstant.REGION_ID, SysConstant.ACCESS_KEY_ID, SysConstant.ACCESS_KEY_SECRET);
 				DefaultProfile.addEndpoint(SysConstant.ENDPOINT_NAME, SysConstant.REGION_ID, SysConstant.PRODUCT, SysConstant.DOMAIN);
 				IAcsClient client = new DefaultAcsClient(profile);
 				//指定规则上传待检数据(语音)
 				UploadAudioDataWithRulesRequest uploadAudioDataRequest = new UploadAudioDataWithRulesRequest();
 		        uploadAudioDataRequest.setAcceptFormat(FormatType.JSON);	        
 				Map<String, Object> map = new HashMap<String, Object>();
 		        
 		        map.put("appKey", SysConstant.APP_KEY);
 		        map.put("callList", callMapList);
 		        map.put("clientChannel", 1);
 		        map.put("sampleRate", 8);
 		        map.put("serviceChannel", 0);
 		        
 		        uploadAudioDataRequest.setJsonStr(JSON.toJSONString(map));
 		       logger.info("---callMapList---"+callMapList);
 		        UploadAudioDataWithRulesResponse response = client.getAcsResponse(uploadAudioDataRequest);
 		        receiveTaskId=response.getData();
 		        
 		        long Id = 0l;
 		        try {
 		            Id = SequenceCreator.getSequence("SCA_TASK_SEQ");
 		       } catch (Exception e) {
 		           logger.error("sequenceCreator obtain SCA_TASK_SEQ occur an error!",e);
 		           return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,ExceptionUtil.getMessage(e));
 		       }
 		        TaskModel aiTask = new TaskModel();
 		        aiTask.setTaskId(Id);
 		        aiTask.setTaskName(sceneName+"-"+time.format(new Date())); //场景名称+当前时间
 		        aiTask.setSetId(Long.parseLong(setIds));
 		        aiTask.setAreaId(Long.parseLong(areaId));
 		        aiTask.setSceneId(Long.parseLong(cId));
 		        aiTask.setStartTime(new Date());
 		        aiTask.setStatus(0);
 		        aiTask.setAlitaskid(receiveTaskId);
 	
 		        try {
 		            this.taskService.addTask(aiTask);
 		        } catch (Exception e) {
 		            logger.error("create SCA_TASK occur an error !",e);
 		            return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,ExceptionUtil.getMessage(e));
 		        }
 		         
 		        try {
 					this.taskService.updateAudioSourceTask(listUpdate);
 				} catch (Exception e) {
 					 logger.error(" updateAudioSourceTask occur an error!",e);
 					 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
 				}
 		        //音频源质检结果，音频与任务关系
 		         List<ScaAudioResult> listAddAudioResult = new ArrayList<ScaAudioResult>();
 		         List<TaskAudioRelaModel> listAddAudioTask = new ArrayList<TaskAudioRelaModel>();
 		         Long taskId=Id;
 		         if(audioSourceStr!=null&&audioSourceStr.size()>0){
 		 	        for(AudioSourceDto  stu :  audioSourceStr ){
 		 		       Long fileId=stu.getFile_Id();
 		 		       listAddAudioTask.add(new TaskAudioRelaModel(fileId,taskId));
 		 		       
 		 		       Long resultId=SequenceCreator.getSequence("SCA_AUDIO_RESULT_SEQ");
 		 		       listAddAudioResult.add(new ScaAudioResult(resultId,fileId));
 		 	        }
 	 		        try {
 	 					this.taskService.addAudioTask(listAddAudioTask);
 	 					this.taskService.addAudioResult(listAddAudioResult);
 	 				} catch (Exception e) {
 	 					 logger.error(" addAudioTask addAudioResult    occur an error!",e);
 	 					 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
 	 				}
 		         }
 		        
 			}catch (ServerException e) {
 				return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,ExceptionUtil.getMessage(e));
 			} catch (ClientException e) {
 				return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,ExceptionUtil.getMessage(e));
 			}
 			JSONObject jsonStrAll = new JSONObject();
 			jsonStrAll.put("taskId", receiveTaskId);
 			logger.info(jsonStrAll);
 			return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,jsonStrAll);
         }else{
         	logger.info("没有自动创建任务的音频文件"); 
         }
 		return cId;
	}
}
